package sdu.icat.pj.util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import sdu.icat.pj.support.Constants;

public class TokenUtil {

    static final Logger logger = LogManager.getLogger();
    static ConcurrentMap<String, UsernamePasswordToken> tokens = new ConcurrentHashMap<>();
    
    public static void setTokenInfo(String token,String value) {
	UsernamePasswordToken tok = new UsernamePasswordToken(token, value);
	tokens.put(Constants.TOKEN_KEY+token, tok);
    }
    
    public static UsernamePasswordToken getTokenInfo(String token) {
	UsernamePasswordToken value = tokens.getOrDefault(Constants.TOKEN_KEY+token,null);
	return value;
    }
    
    public static UsernamePasswordToken getTokenInfo(String username,String password) {
	setTokenInfo(username, password);
	return getTokenInfo(username);
    }
    
    public static Map<String,Object> delToken() {
	Map<String,Object> message = new HashMap<>();
	Subject subject = SecurityUtils.getSubject();
	try {
	    subject.logout();
	} catch (Exception e) {
	    message.put("status", false);
	    message.put("msg","抱歉，您的操作有误，注销失败");
	    logger.error("error:"+e.getMessage());
	    return message;
	}
	tokens.remove(Constants.TOKEN_KEY+subject.getPrincipal());  
	message.put("status", true);
	message.put("msg", "注销成功");
	return message;
    }
}
